﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

namespace MobileSales.Website.Infrastructure.Messaging
{
    #region MessageType

    public enum MessageType
    {
        Error,
        Notice,
        Info
    }

    #endregion

    #region Message

    public class Message
    {
        public string Content { get; set; }
        public MessageType Type { get; set; }
    }

    #endregion

    #region MessageHelper
    public static class MessageHelper
    {
        #region MessageBox
        /// <summary>
        /// Creates flash message box which keeps our users informed
        /// </summary>
        /// <param name="helper"></param>
        /// <returns></returns>
        public static MvcHtmlString MessageBox(this HtmlHelper helper, string jsMessageBoxPath)
        {
            List<Message> messages = new List<Message>();
            if (helper.ViewContext.TempData["info-messages"] != null)
            {
                messages.AddRange((List<Message>)helper.ViewContext.TempData["info-messages"]);
            }
            else if (helper.ViewContext.TempData["notice-messages"] != null)
            {
                messages.AddRange((List<Message>)helper.ViewContext.TempData["notice-messages"]);
            }
            else if (helper.ViewContext.TempData["error-messages"] != null)
            {
                messages.AddRange((List<Message>)helper.ViewContext.TempData["error-messages"]);
            }
            var sb = new StringBuilder();
            sb.AppendFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", jsMessageBoxPath);
            if (messages.Count > 0)
            {
                sb.AppendLine("<script>");
                sb.AppendLine("$(document).ready(function() {");
                foreach (var m in messages)
                {
                    sb.AppendFormat("showMessage('{0}','{1}'); ", HttpUtility.HtmlEncode(m.Content).Replace("\n","<br/>"), m.Type.ToString());
                }
                sb.AppendLine("});");
                sb.AppendLine("</script>");
            }
            sb.AppendLine("<div id=\"messageBoxOverlay\"></div>");
            sb.AppendLine("<div id=\"messageBox\" class=\"ui-corner-all\"></div>");
            return MvcHtmlString.Create(sb.ToString());
        }
        #endregion
    } 
    #endregion
}